<template>
  <!-- 图片上传 -->
  <el-upload
    ref="upload"
    name="multipartFiles"
    :action="action"
    :before-upload="handelCheckFile"
    :on-success="onSuccess"
    :on-error="onError"
    :on-change="onChange"
    :multiple="multiple"
    :accept="accept"
    :autoUpload="autoUpload"
    :file-list="fileList"
    :limit="limit"
    list-type="picture"
  >
    <el-button size="small" type="primary" :disabled="fileList.length >= limit"
      >点击上传</el-button
    >
    <div slot="tip" class="el-upload__tip">
      只能上传jpg/png/gif文件，且不超过{{ fileSize }}M!
    </div>
  </el-upload>
</template>

<script>
// 允许上传的文件类型
// eslint-disable-next-line no-undef
const fileType = [
  "image/jpg",
  "image/jpeg",
  "image/png",
  "image/bmp",
  "image/gif",
].join(",");
export default {
  props: {
    // 是否支持多选
    multiple: {
      type: Boolean,
      default: false,
    },
    // 接受上传的文件类型（thumbnail-mode 模式下此参数无效）
    accept: {
      type: String,
      default: fileType,
    },
    // 文件上传地址
    action: {
      type: String,
      default: "",
    },
    // 是否在选取文件后立即进行上传
    autoUpload: {
      type: Boolean,
      default: false,
    },
    // 最大允许上传个数
    limit: {
      type: Number,
      default: 1,
    },
    // 限制文件大小 单位M
    fileSize: {
      type: String,
      default: "2",
    },
  },
  data() {
    return {
      fileList: [],
    };
  },
  methods: {
    handelCheckFile(file) {
      let totalSize = file.size / 1024 / 1024;
      let errMessage = "";
      const isOverSize = totalSize > Number(this.fileSize);
      const sizeZero = totalSize === 0;
      if (errMessage) {
        this.$message.warning(errMessage);
        this.onError();
        return false;
      } else if (isOverSize) {
        this.$message.warning("文件大小超过" + this.fileSize + "M！");
        this.onError();
        return false;
      } else if (sizeZero) {
        this.$message.warning("文件无内容！");
        this.onError();
        return false;
      }
      // 添加文件
      this.fileList.push(file);
    },

    // 上传到服务器
    submitUpload() {
      this.$refs.upload.submit();
    },

    // 上传成功回调
    onSuccess(data) {
      let res = data.result;
      let nd = [];
      res.mFilePath.forEach((path, index) => {
        nd.push({
          id: res.idList[index],
          name: res.mFileName[index],
          url: path,
        });
      });
      this.$emit("callBackImg", nd);
      this.clearData();
    },

    // 上传失败
    onError() {
      this.$message({
        message: `上传失败！`,
        type: "error",
      });
      this.$emit("callBackError");
    },

    // 文件变动
    onChange() {
      this.$emit("callBackChange");
    },
    // 清除数据
    clearData() {
      this.fileList = [];
      this.$refs.upload.clearFiles();
    },
  },
};
</script>
